<template>
  <div class="BManagement">
    <div class="div-title">
      <p class="p-title">计费管理 / 缴费类性管理</p>
    </div>
    <div class="content">
      <!-- 搜索栏 -->
      <div class="content-top">
        <el-form
          ref="form"
          :model="form"
          label-width="80px"
          class="search-form"
        >
          <div class="Search-left">
            <el-input
              v-model="form.name"
              placeholder="项目价格"
              style="width: 235px"
            ></el-input>
          </div>
          <div class="Search-cont">
            <el-select
              v-model="form.region"
              placeholder="通知状态"
              style="width: 235px"
            >
              <el-option label="已通知" value="1"></el-option>
              <el-option label="未通知" value="2"></el-option>
            </el-select>
          </div>
          <div class="Search-right">
            <div class="Search-h1">
              <h1>{{ currentTitle }}</h1>
            </div>
            <div class="Search-button">
              <el-button type="primary" @click="Search" icon="el-icon-search"
                >查询</el-button
              >
              <el-button
                type="primary"
                @click="handleAdd"
                icon="el-icon-plus"
                style="background-color: #67c23a; border: none"
                >新增</el-button
              >
              <el-button
                type="primary"
                @click="resetSearch"
                icon="el-icon-refresh"
                >刷新</el-button
              >
              <el-button
                type="primary"
                @click="handleExport"
                icon="el-icon-upload2"
                >导出</el-button
              >
            </div>
          </div>
        </el-form>
      </div>
      <div class="content-body">
        <!-- 树形控件 -->
        <div class="left-content">
          <el-tree
            :data="data"
            :props="defaultProps"
            @node-click="handleNodeClick"
          ></el-tree>
        </div>
        <!-- 表格 -->
        <div class="right-content">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column
              prop="payname"
              label="缴费项目名称"
            ></el-table-column>
            <el-table-column
              prop="paylevel"
              label="缴费项目优先级"
            ></el-table-column>
            <el-table-column prop="paynum" label="项目用量/时长">
            </el-table-column>
            <el-table-column prop="paymoney" label="项目价格" sortable>
            </el-table-column>
            <el-table-column prop="paytime" label="创建时间" sortable>
              <template #default="scope">
                {{ formatDate(scope.row.paytime) }}
              </template>
            </el-table-column>
            <el-table-column prop="username" label="通知人">
              <template #default="scope">
                {{ scope.row.username || "暂无" }}
              </template>
            </el-table-column>
            <el-table-column prop="paystatus" label="状态">
              <template #default="scope">
                <span v-if="scope.row.paystatus == 1">已通知</span>
                <span v-else-if="scope.row.paystatus == 2">未通知</span>
                <span v-else>未知状态</span>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="操作" width="220">
              <template #default="scope">
                <div style="white-space: nowrap">
                  <el-button
                    size="mini"
                    @click="ModelSearch(scope.$index, scope.row)"
                    >通知</el-button
                  >
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                    >查看</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >作废</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="block">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage1"
              :page-sizes="[9, 10, 20, 50]"
              :page-size="size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <!-- 模态框 -->
    <div class="Modal" ref="Modal">
      <!-- 通知 -->
      <div class="notice">
        <div class="notice-top">
          <div class="top-left">
            <h1>计费通知</h1>
          </div>
          <div class="top-right">
            <span @click="closeModal" style="cursor: pointer">×</span>
          </div>
        </div>
        <div class="notice-body">
          <div class="body-top">
            <el-form ref="form" :model="Modelform" class="modal-form">
              <el-form-item class="form-item-inline">
                <el-input
                  v-model="Modelform.name"
                  style="width: 300px"
                  placeholder="请输入用户账号"
                ></el-input>
              </el-form-item>
              <el-form-item class="form-item-inline" style="margin-left: 20px">
                <el-button
                  type="primary"
                  @click="ModelSearch"
                  icon="el-icon-search"
                ></el-button>
                <el-button @click="ModelReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="body-bottom">
            <el-table :data="ModeltableData" border style="width: 100%">
              <el-table-column
                type="index"
                width="50"
                label="序号"
              ></el-table-column>
              <el-table-column
                prop="username"
                label="用户账号"
              ></el-table-column>
              <el-table-column prop="homeaddress" label="家庭住址">
              </el-table-column>
              <el-table-column prop="type" label="类型">
                <template #default="scope">
                  <span v-if="scope.row.type == 1">管理员</span>
                  <span v-else-if="scope.row.type == 2">普通用户</span>
                  <span v-else></span>
                </template>
              </el-table-column>
              <el-table-column prop="coststatus" label="缴费状态">
                <template #default="scope">
                  <span v-if="scope.row.coststatus == 1">已缴费</span>
                  <span v-else-if="scope.row.coststatus == 2">未缴费</span>
                </template>
              </el-table-column>
            </el-table>
            <!-- 模态框中的分页 -->
            <div class="block">
              <el-pagination
                @size-change="ModelhandleSizeChange"
                @current-change="ModelhandleCurrentChange"
                :current-page="ModelcurrentPage1"
                :page-sizes="[5, 10, 20, 30]"
                :page-size="Modelsize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="Modeltotal"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import * as XLSX from "xlsx"; // 添加这行导入语句
import { saveAs } from "file-saver";

export default {
  data() {
    return {
      // 搜索框
      form: {
        name: "",
        region: "",
      },
      // 模态库昂
      Modelform: {
        name: "",
      },
      ModeltableData: [],
      // 树状控件
      data: [
        {
          label: "缴费项目",
          children: [
            {
              label: "电费项目",
              children: [
                {
                  label: "电费目录表",
                },
              ],
            },
            {
              label: "水费项目",
              children: [
                {
                  label: "水费固定月目录表",
                },
                {
                  label: "水费按计价目录表",
                },
              ],
            },
            {
              label: "天然气项目",
              children: [
                {
                  label: "天然气目录表",
                },
              ],
            },
            {
              label: "物业费项目",
              children: [
                {
                  label: "物业费目录表",
                },
              ],
            },
            {
              label: "宽带费项目",
              children: [
                {
                  label: "宽带费目录表",
                },
              ],
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      currentTreeItem: null, // 新增：当前选中的树节点
      currentTitle: "电费目录", // 新增：当前显示的标题
      // 分页
      currentPage1: 1,
      total: 0,
      size: 10,
      // 模态框中的分页
      ModelcurrentPage1: 1,
      Modeltotal: 0,
      Modelsize: 10,
      // 表格数据
      tableData: [],
    };
  },
  methods: {
    // 搜索栏
    Search() {
      this.currentPage1 = 1;
      this.refreshData();

      if (!this.currentTreeItem) {
        this.EBlist(); // 默认加载电费数据
        return;
      }
      switch (this.currentTreeItem) {
        case "电费目录表":
          this.EBlist();
          break;
        case "水费固定月目录表":
          this.WMlist();
          break;
        case "水费按计价目录表":
          this.WDlist();
          break;
        case "天然气目录表":
          this.NGlist();
          break;
        case "物业费目录表":
          this.SFlist();
          break;
        case "宽带费目录表":
          this.BFlist();
          break;
        default:
          this.EBlist();
          break;
      }
    },
    // 新增
    handleAdd() {
      this.$router.push({
        path: "/payAdd",
        query: {
          type: "ADD", // 操作类型：编辑
          paystatus: 2, // 传递项目ID
        },
      });
    },
    // 导出
    handleExport() {
      // 准备导出数据
      const exportData = this.tableData.map((item) => ({
        缴费项目名称: item.payname,
        缴费项目优先级: item.paylevel,
        "项目用量/时长": item.paynum,
        项目价格: item.paymoney,
        创建时间: this.formatDate(item.paytime),
        通知人: item.username || "暂无",
        状态:
          item.paystatus == 1
            ? "已通知"
            : item.paystatus == 2
            ? "未通知"
            : "未知状态",
      }));

      // 创建工作簿
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(
        workbook,
        worksheet,
        this.currentTitle || "缴费数据"
      );

      // 生成Excel文件
      const excelBuffer = XLSX.write(workbook, {
        bookType: "xlsx",
        type: "array",
      });
      const data = new Blob([excelBuffer], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });

      // 获取当前日期作为文件名的一部分
      const today = new Date();
      const dateString = `${today.getFullYear()}${String(
        today.getMonth() + 1
      ).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;

      // 保存文件
      saveAs(data, `${this.currentTitle || "缴费数据"}_${dateString}.xlsx`);

      this.$message({
        message: "导出成功",
        type: "success",
      });
    },
    // 左边树状控件
    handleNodeClick(data) {
      console.log(data);
      this.currentTreeItem = data.label; // 记录当前选中的节点

      // 根据不同的节点调用不同的数据获取方法
      switch (data.label) {
        case "电费目录表":
          (this.currentTitle = "电费目录"), this.EBlist();
          break;
        case "水费固定月目录表":
          (this.currentTitle = "水费固定月目录表"), this.WMlist();
          break;
        case "水费按计价目录表":
          (this.currentTitle = "水费按计价目录表"), this.WDlist();
          break;
        case "天然气目录表":
          (this.currentTitle = "天然气目录表"), this.NGlist();
          break;
        case "物业费目录表":
          (this.currentTitle = "物业费目录表"), this.SFlist();
          break;
        case "宽带费目录表":
          (this.currentTitle = "宽带费目录表"), this.BFlist();
          break;
        default:
          // 默认处理或不做处理
          break;
      }
    },
    refreshData() {
      if (!this.currentTreeItem) {
        this.EBlist(); // 默认加载电费数据
        return;
      }

      switch (this.currentTreeItem) {
        case "电费目录表":
          this.EBlist();
          break;
        case "水费固定月目录表":
          this.WMlist();
          break;
        case "水费按计价目录表":
          this.WDlist();
          break;
        case "天然气目录表":
          this.NGlist();
          break;
        case "物业费目录表":
          this.SFlist();
          break;
        case "宽带费目录表":
          this.BFlist();
          break;
        default:
          this.EBlist();
          break;
      }
    },
    // 分页
    handleSizeChange(val) {
      this.size = val;
      this.refreshData();
    },
    handleCurrentChange(val) {
      this.currentPage1 = val;
      this.refreshData();
    },
    // 模态框中的分页
    ModelhandleSizeChange(val) {
      this.Modelsize = val;
      this.ModelcurrentPage1 = 1; // 重置到第一页
      this.ModelSearch();
    },
    ModelhandleCurrentChange(val) {
      this.ModelcurrentPage1 = val;
      this.ModelSearch(); // 调用数据获取方法
    },
    // 关闭模态框
    closeModal() {
      this.$refs.Modal.style.display = "none";
    },
    // 表格按钮
    handleEdit(index, row) {
      console.log(index, row);
      this.ModelcurrentPage1 = 1;
      this.Modelsize = 10;
      this.ModelSearch();
      this.$refs.Modal.style.display = "block";

      this.$router.push({
        path: "/payAdd",
        query: {
          type: "DETAIL", // 操作类型：编辑
          detailId: row.id, // 传递项目ID
        },
      });
    },
    handleDelete(index, row) {
      console.log(index, row);
      this.$confirm("确定要作废此缴费项目吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击确定后执行删除
          axios
            .get("http://community.byesame.com/cost/delCostData", {
              params: {
                id: row.id, // 使用行数据的id
                token: localStorage.getItem("token") || "", // 从本地存储获取token或使用空字符串
              },
            })
            .then((res) => {
              console.log("删除", res.status);
              if (res.status === 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                // 删除成功后刷新数据
                this.refreshData();
              } else {
                this.$message.error(res.data.msg || "删除失败");
              }
            })
            .catch((err) => {
              console.error("删除失败", err);
              this.$message.error("删除失败，请稍后重试");
            });
        })
        .catch(() => {
          // 用户点击取消
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 搜索重置
    resetSearch() {
      this.form = {
        name: "",
        region: "",
      };
      this.currentPage1 = 1;
      this.Search();
    },
    // 模态框重置
    ModelReset() {
      this.Modelform.name = "";
      this.ModelcurrentPage1 = 1;
      this.ModelSearch();
    },
    // 新增日期格式化方法
    formatDate(dateString) {
      if (!dateString) return ""; // 如果日期为空，返回空字符串
      const date = new Date(dateString); // 将字符串转为 Date 对象
      const year = date.getFullYear(); // 获取年份（4位数）
      const month = String(date.getMonth() + 1).padStart(2, "0"); // 获取月份（补零到2位）
      const day = String(date.getDate()).padStart(2, "0"); // 获取日期（补零到2位）
      return `${year}-${day}-${month}`; // 返回格式为 YYYY-DD-MM
    },
    // 电费目录列表
    EBlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 7,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
          },
        })
        .then((res) => {
          console.log("电费", res.data.data);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取列表失败", err);
        });
    },
    // 水费目录表
    WMlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 8,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
            // currPage: 0,
            // pageNum: 9,
          },
        })
        .then((res) => {
          console.log("水费月", res);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取水费月列表失败", err);
        });
    },
    WDlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 9,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
            // currPage: 0,
            // pageNum: 9,
          },
        })
        .then((res) => {
          console.log("水费量", res);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取水费量列表失败", err);
        });
    },
    // 天然气目录表
    NGlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 10,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
          },
        })
        .then((res) => {
          console.log("天然气", res);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取天然气列表失败", err);
        });
    },
    // 物业费目录表
    SFlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 11,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
          },
        })
        .then((res) => {
          console.log("物业费", res);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取物业费列表失败", err);
        });
    },
    //宽带费目录表
    BFlist() {
      axios
        .get("http://community.byesame.com/cost/getCostData", {
          params: {
            c_id: 12,
            paymoney: this.form.name,
            paystatus: this.form.region,
            currPage: this.currentPage1 - 1,
            pageNum: this.size,
          },
        })
        .then((res) => {
          console.log("宽带费", res);
          if (res.status === 200) {
            this.tableData = res.data.data;
            this.total = res.data.total;
          }
        })
        .catch((err) => {
          console.error("获取宽带费列表失败", err);
        });
    },
    // 模态框
    ModelSearch() {
        this.$refs.Modal.style.display = "block"; // 显示模态框
      axios
        .get("http://community.byesame.com/users/getUserList", {
          params: {
            username: this.Modelform.name,
            currPage: this.ModelcurrentPage1 - 1,
            pageNum: this.Modelsize,
          },
        })
        .then((res) => {
          console.log("模态框中的数据", res);
          if (res.status === 200) {
            this.ModeltableData = res.data.data;
            this.Modeltotal = res.data.total;
            console.log("模态框数据", this.ModeltableData);
          }
        })
        .catch((err) => {
          console.error("获取用户列表失败", err);
        });
    },
  },
  created() {
    this.EBlist();
    this.ModelSearch();
  },
};
</script>

<style scoped>
.BManagement {
  padding: 20px;
}
.p-title {
  font-weight: bold;
  font-size: 16px;
}
/* 搜索栏 */
.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
}
.content-top {
  margin: 15px 0px 35px 0px;
}
.Search-left,
.Search-cont,
.Search-right {
  display: flex;
  align-items: center;
}
.Search-right {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-left: 30px;
}
.content-body {
  display: flex;
  gap: 20px;
}
.left-content {
  width: 500px;
  flex-shrink: 0;
}
.right-content {
  flex: 1;
}
/* 分页 */
.block {
  display: flex;
  justify-content: flex-end;
}
/* 模态框 */
.Modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 9999;
  display: none;
}
.notice {
  width: 900px;
  background-color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
}
.notice-top {
  display: flex;
  justify-content: space-between;
  flex-shrink: 0;
  padding-bottom: 15px;
}
.notice-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.body-top {
  margin: 10px 0px;
  flex-shrink: 0;
}
.body-bottom {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.body-bottom .el-table {
  flex: 1;
  overflow-y: auto;
}
.body-bottom .block {
  flex-shrink: 0;
  padding-top: 15px;
}
/* 模态框表单样式 */
.modal-form {
  display: flex;
}

.form-item-inline {
  margin-bottom: 0;
  /* display: flex; */
  align-items: center;
}

.body-top {
  margin: 10px 0px;
}
</style>